<template>
    <div id='subPage'>
        <div class="box">
            <div style="width: 100%;display:flex;justify-content: space-between;align-items: center;margin-bottom: 10px">
                <div class="toBack" @click="$router.push({ path: '/quality/checkTask' })" style="cursor:pointer;"> <span class="el-icon-arrow-left">返回</span></div>
                <div class="operationBox" style="padding: 0;">
                    <div class="tableBtn"  @click="addRowFn(1)">
                        <div class="btnBox">
                            <div class="text">+ 分配任务</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="inputName" style="padding:20px;margin-bottom:10px;border-radius: 4px;">
                <div class="item">
                    <span class="tip">*</span>
                    <span style="color:#777777;">任务名称：</span>
                    <Input v-model="title" placeholder="请输入" show-word-limit :maxlength="maxlength" style="flex:1;" clearable/>
                    <input type="password" autocomplete="new-password" style="display: none" />
                </div>
                <div class="item">
                    <span  style="color:#777777;">检查说明：</span>
                    <Input v-model="content" placeholder="此地区可能存在隐患问题，需仔细检查" show-word-limit :maxlength="maxlength" style="flex:1;" clearable/>
                    <input type="password" autocomplete="new-password" style="display: none" />
                </div>
            </div>
            <div class="bottom">
                <div class="tableBox">
                    <div class="tableList" ref="tableList">
                        <el-table :data="taskList" style="width: 100%;border:1px solid #E9F2F6;" :stripe="true">
                            <template slot="empty">
                                <div class="no_lsit" style="width:96%;margin:auto;">
                                    <img src="./../../assets/images/common/rotary_nodata.png" alt=""
                                         style="width:3.9rem; height: 2.4rem;">
                                </div>
                            </template>
                            <el-table-column prop="userName" label="检查人" align="center"></el-table-column>
                            <el-table-column prop="checkType" label="检查频率" align="center">
                                <template slot-scope="scope">
                                    {{scope.row.checkType == 2 ? '每日检查' : '单次检查'}}
                                </template>
                            </el-table-column>
                            <el-table-column prop="timeList" label="计划检查时间" width="300px" >
                                <template slot-scope="scope">
                                    <div v-if="scope.row.checkType == 2">
                                        <Tooltip  transfer :content="scope.row.timeList.length > 0 ? scope.row.timeList.join(',') : '—'" placement="top-start"  max-width='245'>
                                    <p style="width:280px;overflow: hidden;text-overflow:ellipsis;white-space:nowrap;cursor: pointer;">
                                        {{scope.row.timeList.length > 0 ? scope.row.timeList.join(',') : '—'}}
                                    </p>
                                    </Tooltip>
                                    </div>
                                    <p v-else>
                                        {{scope.row.timeList[0]}}至{{scope.row.timeList[1]}}
                                    </p>
                                </template>
                            </el-table-column>
                            <el-table-column prop="partArr" label="检查部位"  width="300px">
                                <template slot-scope="scope">
                                    <Tooltip  transfer :content="scope.row.partNameList.length > 0 ? scope.row.partNameList.join(',') : '—'" placement="top-start"  max-width='200'>
                                        <p style="width:280px;overflow: hidden;text-overflow:ellipsis;white-space:nowrap;cursor: pointer;">
                                            {{scope.row.partNameList.length > 0 ? scope.row.partNameList.join(',') : '—'}}
                                        </p>
                                    </Tooltip>
                                </template>
                            </el-table-column>
                            <el-table-column  label="操作" align="center"  width='200px'>
                                <template slot-scope="scope">
                                    <el-button style="color:#0382F8" type="text" size="small" @click.native.prevent="addRowFn(2,scope.$index, taskList)" >编辑</el-button>
                                    <el-button style="color:#FF0000" @click.native.prevent="removeFn(scope.$index, taskList,1)" type="text" size="small">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div class="submitBtn">
                        <div class="button cancel" @click="cancel(2)">取消任务</div>
                        <div class="button submit" @click="submitFn" v-preventReClick="1500">提交任务</div>
                    </div>
                </div>
            </div>
        </div>

        <Modal v-model="modal" :title="isAdd ? '分配检查任务' :'编辑检查任务'" width="700px;" :mask-closable="false" class-name="msgModal">
            <div class="tackAdd">
                <div class="list">
                    <div class="item">
                        <i class="tip">*</i>
                        <span class="span">检查人：</span>
                        <Select v-model="userId" style="flex:1;" placeholder="请选择" filterable>
                            <Option
                                v-for="(item , index) in overdueList"
                                :value="item.id"
                                :key="index"
                            >{{item.nickname}}</Option>
                        </Select>
                    </div>
                    <div class="item">
                        <i class="tip">*</i>
                        <span class="span">检查频率：</span>
                        <RadioGroup v-model="checkType" filterable>
                            <Radio label="1">单次检查</Radio>
                            <Radio label="2">每日检查</Radio>
                        </RadioGroup>
                    </div>
                    <div class="item">
                        <i class="tip">*</i>
                        <span class="span">检查时间：</span>
                        <DatePicker :type="checkType == 2 ? 'date' : 'daterange'" :options="options" :multiple ='checkType == 2' :clearable="true" v-model="timeList" v-if="inputShow" format="yyyy-MM-dd" placement="top" transfer  placeholder="请选择日期" :style="[{'width': checkType == 2 ? 'calc(100% - 90px)' : '300px'}]" @on-change="getDateArr" ></DatePicker>
                        <DatePicker :type="checkType == 2 ? 'date' : 'daterange'" format="yyyy-MM-dd" placement="top"  placeholder="请选择日期" v-if="inputShow" style="opacity:0;position: absolute;top:-9999px;width:1px;"></DatePicker>
                        </div>
                    <div class="item">
                        <i class="tip">*</i>
                        <span class="span">检查部位：</span>
                        <treeselect style="flex:1;" :multiple="true" :options="partIdList" :flat="true" :default-expand-level="1"  placeholder="请选择检查部位"  v-model="partIds"/>
                    </div>
                </div>
            </div>
            <div slot="footer">
                <div class="footer">
                    <div class="button cancel" @click="cancel(1)">取消</div>
                    <div class="button submit" @click="submit" v-preventReClick="1500">确定</div>
                </div >
            </div>

        </Modal>
    </div>
</template>

<script>
import {treeSort , trans , flatten} from '@/sever/config';
import {initYMD} from '@/sever/utils';
import {getUserList,getQualityPartList ,getQualityTaskAdd } from '@/api/quality.js'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
    components: { Treeselect },
    data () {
        return {
            options: {
                disabledDate(date) {
                    return date && date.valueOf() < Date.now() - 86400000;
                }
            },
            btnList:[],
            taskList:[],
            maxlength:25,
            limitlength:32,
            deptId:"",
            deptName:"",
            modal:false,
            inputShow:false,
            isAdd:true,
            overdueList:[],
            partIdList:[],//树形结构检查部位数组
            flattenList:[],//扁平化检查部位数组
            title:"",
            content:"此地区可能存在隐患问题，需仔细检查",
            userName:"",
            userId:"",
            checkType:"1",
            partIds:[],
            timeList:[],
            editIdnex :'',
        }
    },
    computed: {
        porjectObject() {
            return this.$store.state.porjectObject;
        },
    },
    watch: {
        porjectObject(val, oldVal) {
            if (val.deptId != oldVal.deptId) {
                this.deptId = val.deptId;
                this.editIdnex ='';
                this.getChecktPartList();
                this.getUserListFn();
            }
        },
    },
    methods: {
        addRowFn(type , index, rows){
            this.modal = true;
            if(type == 1){
                this.userName = "";
                this.userId = "";
                this.checkType = "1";
                this.timeList = [];
                this.partIds = [];
                this.isAdd = true;
                this.editIdnex ='';
            }else{
                this.userName = rows[index].userName;
                this.userId = rows[index].userId;
                this.checkType = rows[index].checkType;
                this.timeList = rows[index].timeList;
                this.partIds = rows[index].partIdList;
                this.isAdd = false;
                this.editIdnex = index;
            }
        },
        getDateArr(i,v){
            this.timeList = i;
        },
        // 请求检查人列表
        getUserListFn() {
            let params = {
                deptId:this.deptId
            };
            getUserList(params)
                .then(res => {
                    if (res.code == 200) {
                        this.overdueList = res.data;
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        //获取检查部位
        getChecktPartList() {
            let params = {
                deptId: this.deptId
            };
            getQualityPartList(params)
                .then(res => {
                    if (res.code == 200) {
                        let arr = res.data.list;
                        this.partIdList = treeSort(trans(arr));
                        let flattenList = JSON.stringify(treeSort(trans(arr)));
                        this.flattenList = flatten(JSON.parse(flattenList));
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        // 提交数据到表格
        submit(){
            if(!this.userId){
                this.$Modal.warning({
                    title: "您有必选字段",
                    content: "检查人不能为空"
                });
                return;
            }
            if(this.timeList.length == 0){
                this.$Modal.warning({
                    title: "您有必选字段",
                    content: "检查时间不能为空"
                });
                return;
            }
            if(this.partIds.length == 0){
                this.$Modal.warning({
                    title: "您有必选字段",
                    content: "检查部位不能为空"
                });
                return;
            }
            let partNameList = [];
            this.partIds.forEach(v => {
                this.flattenList.forEach(item => {
                    if(v == item.id){
                        partNameList.push(item.name);
                    }
                })
            })
            let timeList = [];
            if(this.checkType == 2){
                let timeListArr = [];
                if(this.timeList instanceof Array){
                    timeListArr = this.timeList;
                }else{
                    timeListArr = this.timeList.split(',');
                }
                let timeListArrSort = [];
                timeListArr.forEach(v => {
                    timeListArrSort.push(new Date(v).getTime())
                })
                timeListArrSort = timeListArrSort.sort((a,b)=> {return a-b});
                timeListArrSort.forEach(v => {
                    timeList.push(initYMD(v))
                });
            }else{
                timeList = this.timeList;
            }
            this.overdueList.forEach(v => {
                if(this.userId == v.id){
                    this.userName = v.nickname;
                }
            })
            if(this.isAdd){
                let obj = {
                    userId : this.userId,
                    userName : this.userName,
                    checkType : this.checkType,
                    timeList : timeList,
                    partIdList : this.partIds,
                    partNameList : partNameList,
                };
                this.taskList.push(obj);
            }else{
                let arr = this.taskList;
                let copyArr = [];
                arr.forEach((v , i )=>{
                    if(i == this.editIdnex){
                        let obj = {
                            userId : this.userId,
                            userName : this.userName,
                            checkType : this.checkType,
                            timeList : timeList,
                            partIdList : this.partIds,
                            partNameList : partNameList,
                        };
                        copyArr.push(obj);
                    }else{
                        copyArr.push(v);
                    }
                })
                this.taskList = copyArr;
            }
            this.modal = false;
        },
        // 提交数据到数据库
        submitFn(){
            if(!this.title){
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "检查名称不能为空"
                });
                return;
            }
            if(this.taskList.length > 0 ){
                let params = {
                    deptId : this.deptId,
                    content : this.content,
                    title : this.title,
                    taskList : this.taskList,
                }
                getQualityTaskAdd(params)
                .then(res => {
                    if (res.code == 200) {
                        this.$router.push({ path: '/quality/checkTask' })
                        this.$Message.success("操作成功");
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
            }else{
                this.$Modal.warning({
                    title: "提示",
                    content: "请添加分配任务"
                });
                return;
            }
        },
        cancel(i){
            if(i == 1){
                this.modal = false;
            }else if(i == 2){
                this.taskList = [];
                this.$router.push({ path: '/quality/checkTask' })
            }
        },
        removeFn(index,rows,type) {
            if(type == 1){
                this.taskList.splice(index,1);
            }
        },
    },
    mounted(){
        this.deptId = this.$store.state.porjectObject.deptId;
        this.deptName = this.$store.state.porjectObject.name;
        this.btnList = JSON.parse(localStorage.getItem("arr"));
        this.taskList = [];
        this.getChecktPartList();
        this.getUserListFn();
        setTimeout(()=>{
            this.inputShow = true;
        },1)
    },
}
</script>

<style scoped lang="less">
@import "./../../assets/style/themeBase.less";
</style>

<style scoped lang='scss'>
@import "./../../assets/style/qualityAndSafety/checktask.scss";
@import "./../../assets/style/qualityAndSafety/modal.scss";
@function pxToRem($val) {
    @return $val/100 + rem;
}
/deep/ .tackAdd{
    .list{
        width: 90%;
        margin: auto;
        .item{
            position: relative;
            display: flex;
            justify-content: flex-start;
            align-items: center;
            margin-bottom: 15px;
            .span{
                width: 90px;
            }
            .tip{
                // position: absolute;
                // left: -5px;
                // top: -5px;
                color: red;
                margin-right:6px;
            }
        }
    }
}
</style>
